<?php

namespace App\exception;

use Throwable;
use Webman\Exception\ExceptionHandler;
use Webman\Http\Request;
use Webman\Http\Response;

class Handler extends ExceptionHandler
{
    //不记录的
    public $dontReport = [
        HttpResponseException::class
    ];

    public function report(Throwable $e)
    {
        if ($this->shouldntReport($e)) {
            return;
        }
        return;
        $logs = '';
        if ($request = \request()) {
            $logs = $request->getRealIp() . ' ' . $request->method() . ' ' . \trim($request->fullUrl(), '/');
        }
        $this->_logger->error($logs . PHP_EOL . $e);
    }

    public function render(Request $request, Throwable $e): Response
    {
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } else {//其他错误返回和记录
            $msg = $e->getMessage();
            $encode = mb_detect_encoding($msg, ['ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5']);
            if ($encode == "EUC-CN") $msg = iconv($encode, "utf-8", $msg);

            $request_id = uniqid(config('app.node'));
            $logs = '[' . $request_id . '] ' . $request->getRealIp() . ' ' . $request->method() . ' ' . $request->url() . ' code:' . $e->getCode() . ' msg:' . $msg . ' file:' . $e->getFile() . ' line:' . $e->getLine();
            $context = [  //请求
                'path' => $request->path(),
                'controller' => $request->controller,
                'action' => $request->action,
                'header' => $request->header('Authorization', ''),
                'param' => $request->all()
            ];
            if (config('app.debug')) {
                $json = [
                    'code' => 500,
                    'data' => [
                        'request_id' => $request_id,
                        'method' => $request->method(),
                        'url' => $request->url(),
                        'code' => $e->getCode(),
                        'msg' => $msg,
                        'file' => $e->getFile(),
                        'line' => $e->getLine(),
                        'request' => $context
                    ],
                    'msg' => 'Server internal error'
                ];
            } else {
                $json = ['code' => 500, 'data' => ['request_id' => $request_id], 'msg' => '网络错误！'];
            }
            $this->_logger->error($logs . PHP_EOL, $context);
            return json($json);
        }
    }
}